package me.edzh.spring.bootstrap.resolvers;

import me.edzh.spring.bootstrap.annotations.CurrentUserId;
import me.edzh.spring.bootstrap.utils.Constants;
import org.apache.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class CurrentUserIdResolver implements HandlerMethodArgumentResolver {

    private final static Logger logger = Logger.getLogger(CurrentUserIdResolver.class);


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果参数类型是String并且有CurrentUserId注解则支持
        if (methodParameter.getParameterType().isAssignableFrom(String.class) &&
                methodParameter.hasParameterAnnotation(CurrentUserId.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        return (String)nativeWebRequest.getAttribute(Constants.KEY_REQUEST_USER_ID, RequestAttributes.SCOPE_REQUEST);
    }
}
